<?php

namespace app\exception;

use app\enum\ResponseEnum;
use Next\VarDumper\Dumper;
use Next\VarDumper\DumperHandler;
use Throwable;
use Webman\Exception\ExceptionHandler;
use Webman\Http\Request;
use Webman\Http\Response;

/**
 * @desc    全局异常处理
 * @author  OverMiracle
 * @date    2023-12-10
 */
class GlobalExceptionHandler extends ExceptionHandler
{
    use DumperHandler;

    public function render(Request $request, Throwable $exception): Response
    {
        if ($exception instanceof Dumper) {
            return response(self::convertToHtml($exception));
        }
        if (config('app.debug')) {
            return json([
                'code' => ResponseEnum::ERROR,
                'msg'  => $exception->getMessage() ?? '系统异常',
                'data' => [
                    'file'  => $exception->getFile(),
                    'line'  => $exception->getLine(),
                    'trace' => $exception->getTraceAsString()
                ]
            ]);
        }
        return json([
            'code' => ResponseEnum::ERROR,
            'msg'  => $exception->getMessage() ?? '系统异常',
            'data' => [
                'file' => $exception->getFile(),
                'line' => $exception->getLine(),
            ]
        ]);

    }
}